import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {PageContainer, ProDescriptions, ProList, ProTable,} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, Drawer, Dropdown, Input, Layout, Menu, message, Space, Tag, Tooltip} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import Sider from "antd/es/layout/Sider";
import {SortOrder} from "antd/es/table/interface";
import {listProjectUsingPost} from "@/services/easyapi/eProject";
import {interfaceOperationUsingPost, pageInterfaceInfoUsingPost} from "@/services/easyapi/eApiManage";
import {DownOutlined} from "@ant-design/icons";
import GenerateModal from "@/pages/ApiManage/components/GenerateModal";
import { RightSquareOutlined } from '@ant-design/icons';




const ApiManage: React.FC = () => {
  const menu = (
    <Menu>
      {/* eslint-disable-next-line @typescript-eslint/no-use-before-define */}
      <Menu.Item key="generateApi" onClick={() => {
        setGenerateVisible(true)
      }}>
        生成 API
      </Menu.Item>
      <Menu.Item key="registerApi" onClick={() => console.log('注册 API')}>
        注册 API
      </Menu.Item>
    </Menu>
  );
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.ApiInfoPageVo>();
  const [generateVisible, setGenerateVisible] = useState<boolean>(false)
  const [dataSource, setDataSource] = useState<API.ProjectListVo[]>([]);
  const [item, setItem] = useState<API.ProjectListVo>()
  const [projectName, setProjectName] = useState<string>('')
  const [visible, setVisible] = useState(false);


  const columns: ProColumns<API.ApiInfoPageVo>[] = [
    {
      title: '接口名称',
      dataIndex: 'apiNameCn',
      formItemProps: {
        rules: [
          {required: true, message: '请输入接口名称'},
          {min: 1, message: '搜索长度不能够小于1'},
          {max: 255, message: '搜索长度不能够大于255'}
        ]
      }
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      hideInSearch: true,
    },
    {
      title: '接口状态',
      dataIndex: 'apiStatus',
      valueEnum: {
        0: {
          text: '初始化',
          status: 'Processing'
        },
        1: {
          text: '初始化成功',
          status: 'Success'
        },
        2: {
          text: '初始化失败',
          status: 'Error'
        },
        3: {
          text: '在线',
          status: 'Processing'
        },
        4: {
          text: '禁用',
          status: 'Default'
        },
        5: {
          text: '下线',
          status: 'Default'
        }
      }
    },
    {
      title: 'api 提交状态',
      dataIndex: 'testStatus',
      valueEnum: {
        0: {
          text: '未提交',
          status: 'Error'
        },
        1: {
          text: '已提交',
          status: 'Success'
        }
      }
    },
    {
      title: 'api 类型',
      dataIndex: 'apiType',
      valueEnum: {
        0: {
          text: '生成',
          status: 'Success'
        },
        1: {
          text: '注册',
          status: 'Success'
        },
      }
    },
    {
      title: '数据源类型',
      dataIndex: 'dataSrcType',
      hideInSearch: true,
      renderText: (text) => {
        return (
          <Space size={0}>
            <Tag color="#5BD8A6">{text}</Tag>
          </Space>
        )
      }
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="detail"
          onClick={() => {

          }}
        >
          详情
        </a>,
        record.apiStatus===3?
          <a
            key="datasource"
            onClick={async () => {
              const res  = await interfaceOperationUsingPost({
                id: record.id,
                action:'offline'
              })
              if (res.code===200){
                  message.success('下线成功')
              } else{
                message.error(res.msg)
              }
              actionRef.current?.reload()
            }}
            style={{color:'red'}}
          >
            下线
          </a>
          :
          <a
          key={"online"}
          onClick={async ()=>{
            const res = await interfaceOperationUsingPost({
              id:record.id,
              action:'online'
            })
            if (res.code===200){
              message.success('上线成功')
            } else{
              message.error(res.msg)
            }
            actionRef.current?.reload()
          }}
          style={{color:'green'}}
          >
            上线
          </a>,
        <a
          key="update"
          onClick={() => {

          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          style={{color:'red'}}
          onClick={() => {

          }}
        >
          删除
        </a>]
    }
  ]

  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-use-before-define
    fetchProjectList()
  }, []);

  const fetchProjectList = async () => {
    const res = await listProjectUsingPost({
      projectName: projectName
    })
    if (res.code === 200) {
      //@ts-ignore
      setDataSource(res.data)
    } else {
      setDataSource([])
    }
  }
// 定义列配置
  return (
    <Layout style={{height: '100vh', background: 'black'}}>
      <div
        style={{
          position: 'fixed',
          top: '50%',
          left: visible ? '220px' : '0',
          transform: 'translateY(-50%)',
          backgroundColor: 'rgba(0,0,0,0.5)',
          padding: '8px',
          cursor: 'pointer',
          zIndex: 1000, // 确保按钮显示在其他组件之上
          borderRadius: '0 4px 4px 0',
        }}
        onClick={() => setVisible(!visible)}
      >
        <>
          <Tooltip style={{color:'red'}} title={"点击展开项目列表"}>
            <RightSquareOutlined  style={{color: '#d11111', fontSize: '20px'}}/>
          </Tooltip>
        </>
      </div>
      <Drawer
        title="项目列表"
        placement="left"
        width={220}
        onClose={() => setVisible(false)}
        visible={visible}
        bodyStyle={{
          padding: '1px',
          backgroundColor: 'rgba(0,0,0,0.94)',
        }}
        mask={false} // 关闭遮罩
      >
        <Sider
          width={220}
          style={{
            backgroundColor: 'rgba(0,0,0,0.94)',
            borderRight: '1px solid #f0f0f0',
            padding: '1px',
            overflow: 'auto', // Add overflow here to enable scrolling
            height: '100%' // Ensures the Sider takes up the full viewport height
          }}
        >
          <Input.Search
            placeholder="搜索项目"
            value={projectName}
            onChange={(e) => setProjectName(e.target.value)}
            style={{marginBottom: '16px'}}
            onSearch={() => {
              fetchProjectList()
            }}
            enterButton={true}
          />
          <ProList<API.ProjectListVo>
            rowKey="id"
            dataSource={dataSource}
            showActions="hover"
            editable={{
              onSave: async (key, record, originRow) => {
                console.log(key, record, originRow);
                return true;
              },
            }}
            onItem={(item, index) => {
              return {
                onClick: () => {
                  setItem(item)
                  actionRef.current?.reload();
                },
              }
            }}
            onDataSourceChange={setDataSource}
            metas={{
              title: {
                dataIndex: 'projectName',
              },
              description: {
                dataIndex: 'projectDesc',
                render: (desc) => {
                  return (
                    <div
                      style={{
                        maxWidth: '200px', // 限制最大宽度
                        whiteSpace: 'nowrap', // 禁止换行
                        overflow: 'hidden', // 隐藏超出部分
                        textOverflow: 'ellipsis', // 添加省略号
                      }}
                    >{desc}</div>
                  )
                }
              },
              subTitle: {
                render: () => {
                  return (
                    <Space size={0}>
                      <Tag color="#5BD8A6">EasyApi</Tag>
                    </Space>
                  );
                },
              },
            }}
          />
        </Sider>
      </Drawer>
      {/* 旁边的组件 */}
      <div
        style={{
          flex: 1,
          marginLeft: visible ? '220px' : '0', // 根据抽屉状态调整边距
          transition: 'margin-left 0.3s ease', // 添加过渡动画
        }}
      >
      <Layout style={{padding: '2px', backgroundColor: '#fff'}}>
        <PageContainer>
          <ProTable<API.ApiInfoPageVo, API.ApiInfoPageParam>
            actionRef={actionRef}
            rowKey="key"
            search={{
              labelWidth: 120,
            }}
            toolBarRender={() => [
              <Dropdown key="add" overlay={menu} trigger={['click']}>
                <Button type="primary">
                  创建api <DownOutlined/>
                </Button>
              </Dropdown>,
            ]}
            request={async (params
              , sort: Record<string, SortOrder>, filter: Record<string, React.ReactText[] | null>) => {
              // 表单搜索项会从 params 传入，传递给后端接口。
              const res = await pageInterfaceInfoUsingPost({
                ...params,
                projectId: item?.id
              } as API.ApiInfoPageVo);
              if (res.code === 200) {
                return {
                  // @ts-ignore
                  data: res?.data.records,
                  success: true,
                  // @ts-ignore
                  total: res?.data.total,
                };
              } else {
                return {
                  data: [],
                  success: false,
                  total: 0,
                };
              }
            }}
            columns={columns}
          />
          <Drawer
            width={600}
            open={showDetail}
            onClose={() => {
              setCurrentRow(undefined);
              setShowDetail(false);
            }}
            closable={false}
          >
            {currentRow?.apiNameCn && (
              <ProDescriptions<API.RuleListItem>
                column={2}
                title={currentRow?.apiNameCn}
                request={async () => ({
                  data: currentRow || {},
                })}
                params={{
                  id: currentRow?.id,
                }}
                columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
              />
            )}
          </Drawer>
          <GenerateModal
            onCancel={() => {
            setGenerateVisible(false)
          }}
            visible={generateVisible}
            //@ts-ignore
            refreshData={() => {
            actionRef.current?.reload();
          }}/>
        </PageContainer>
      </Layout>
      </div>
    </Layout>
  );
};
export default ApiManage;
